﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;

namespace TestCrawler.Http
{
    public class HttpRequest : IHttp
    {
        private WebRequest _request;
        private WebResponse _response;
        private string _host;

        public string ServerUrl { get; set; }
        public string PathUrl { get; set; }
        public string Content { get; set; }

        public HttpRequest(string url)
        {
            _request = WebRequest.Create(url);
            _response = _request.GetResponse();
            _host = _response.ResponseUri.Host;

            ServerUrl = GetServerUrl();
            PathUrl = GetCurrentPath();
            Content = GetAllContent();
        }

        // Content stream
        private string GetAllContent()
        {
            Stream stream = _response.GetResponseStream();
            StreamReader reader = new StreamReader(stream);
            return reader.ReadToEnd();
        }

        //URL to current path 
        private string GetCurrentPath()
        {
            string path = "";
            Match m = Regex.Match(_response.ResponseUri.AbsoluteUri, "/", RegexOptions.RightToLeft);
            if (m == null)
                path = _response.ResponseUri.AbsoluteUri + "/";
            else
                path = _response.ResponseUri.AbsoluteUri.Substring(0, m.Index) + "/";

            return path;
        }

        //URL to server
        private string GetServerUrl()
        {
            string serverUrl = "";
            Match m = Regex.Match(_response.ResponseUri.AbsoluteUri, _host, 
                RegexOptions.RightToLeft | RegexOptions.IgnoreCase);
            if (m == null)
                serverUrl = _response.ResponseUri.AbsoluteUri;
            else
                serverUrl = _response.ResponseUri.AbsoluteUri.Substring(0, m.Index + _host.Length);

            return serverUrl;
        }
    }
}
